import type * as React from "react";

import {
  type SlateElementProps,
  type TTableCellElement,
  type TTableElement,
} from "platejs";

import { BaseTablePlugin } from "@platejs/table";
import { SlateElement } from "platejs";

import { cn } from "@/lib/utils";

export function TableElementStatic({
  children,
  ...props
}: SlateElementProps&lt;TTableElement&gt;) {
  const { disableMarginLeft } = props.editor.getOptions(BaseTablePlugin);
  const marginLeft = disableMarginLeft ? 0 : props.element.marginLeft;

  return (
    &lt;SlateElement
      {...props}
      className="overflow-x-auto py-5"
      style={{ paddingLeft: marginLeft }}
    &gt;
      <div>
        <table>
          <tbody>{children}</tbody>
        </table>
      </div>
    &lt;/SlateElement&gt;
  );
}

export function TableRowElementStatic(props: SlateElementProps) {
  return (
    &lt;SlateElement {...props} as="tr" className="h-full"&gt;
      {props.children}
    &lt;/SlateElement&gt;
  );
}

export function TableCellElementStatic({
  isHeader,
  ...props
}: SlateElementProps&lt;TTableCellElement&gt; & {
  isHeader?: boolean;
}) {
  const { editor, element } = props;
  const { api } = editor.getPlugin(BaseTablePlugin);

  const { minHeight, width } = api.table.getCellSize({ element });
  const borders = api.table.getCellBorders({ element });

  return (
    &lt;SlateElement
      {...props}
      as={isHeader ? "th" : "td"}
      className={cn(
        "h-full overflow-visible border-none bg-background p-0",
        element.background ? "bg-(--cellBackground)" : "bg-background",
        isHeader && "text-left font-normal *:m-0",
        "before:size-full",
        "before:absolute before:box-border before:content-[''] before:select-none",
        borders &&
          cn(
            borders.bottom?.size && `before:border-b before:border-b-border`,
            borders.right?.size && `before:border-r before:border-r-border`,
            borders.left?.size && `before:border-l before:border-l-border`,
            borders.top?.size && `before:border-t before:border-t-border`,
          ),
      )}
      style={
        {
          "--cellBackground": element.background,
          maxWidth: width || 240,
          minWidth: width || 120,
        } as React.CSSProperties
      }
      attributes={{
        ...props.attributes,
        colSpan: api.table.getColSpan(element),
        rowSpan: api.table.getRowSpan(element),
      }}
    &gt;
      <div style="{{">
        {props.children}
      </div>
    &lt;/SlateElement&gt;
  );
}

export function TableCellHeaderElementStatic(
  props: SlateElementProps&lt;TTableCellElement&gt;,
) {
  return &lt;TableCellElementStatic {...props} isHeader /&gt;;
}
